package com.irssproject.app.service.main.impl;

import java.util.List;

import com.irssproject.app.entitats.User;
import com.irssproject.app.dao.main.iface.UsersDAO;
import com.irssproject.app.service.main.iface.UsersService;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

public class UsersServiceImpl implements UsersService {

    UsersDAO usuariDAO;

    public void setUsersDAO(UsersDAO usuariDAO) {
        this.usuariDAO = usuariDAO;
    }

    private User carregarUsuari(String login) {

        return usuariDAO.getUsuari(login);
    }

    @Transactional(propagation = Propagation.REQUIRED,
    isolation = Isolation.DEFAULT)
    public void deleteUser(User usuari) {

        usuariDAO.deleteUsuari(usuari);
    }

    @Transactional(propagation = Propagation.REQUIRED,
    isolation = Isolation.DEFAULT)
    public Boolean addUser(User usuari) throws Exception {
        return usuariDAO.insertUsuari(usuari);
    }

    @Transactional(propagation = Propagation.REQUIRED,
    isolation = Isolation.DEFAULT)
    public void updateUser(User usuari) throws Exception {
        usuariDAO.updateUsuari(usuari);
    }

    public List<User> getUsersList() {

        return (List<User>) usuariDAO.getListUsuaris();
    }

    public User login(String login, String password) throws Exception {

        User u = new User();
        u.setLogin(login);
        u.setPassword(password);

        User usuari = usuariDAO.autenticarUsuari(u);

        return usuari;
    }

    public boolean existsLogin(String login) {
        if (carregarUsuari(login) == null) {
            return false;
        } else {
            return true;
        }
    }
    
    @Override
    public boolean existsUser(String login, String password) {
    	return usuariDAO.existeixUsuari(login, password);
    }

    @Override
    public User getUserByLogin(String login) {
        return usuariDAO.getUsuari(login);
    }
}
